package com.d6game.web.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ResponseUtil {
	private static Logger logger = LoggerFactory.getLogger(ResponseUtil.class);
	public static void sendDirectResponse(HttpServletResponse response,Object directResponse){
		try {
			logger.debug("send to response directly!");
			if(directResponse instanceof URL){
				URL url = (URL)directResponse;
				int ind = url.getPath().lastIndexOf("/");
				String fileName = url.getPath().substring(ind+1);
				InputStream inputStream = url.openStream();
				sendStreamResponse(response,inputStream,fileName);
			}
			else if(directResponse instanceof File){
				File file = (File)directResponse;
				sendStreamResponse(response,new FileInputStream(file),file.getName());
			}
			else if(directResponse instanceof JsonVO){
				sendJsonResponse(response,(JsonVO)directResponse);
			}
			else{
				sendStringResponse(response,directResponse);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}
	
	public static void sendStreamResponse(HttpServletResponse response,InputStream inputStream,String fileName){
		try {
			response.reset();
			response.setContentType("application/x-download");
			response.addHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
			
			byte[] buf = new byte[4096];
			BufferedInputStream bis = new BufferedInputStream(inputStream);
			ServletOutputStream servletOS = response.getOutputStream();
			try {
				int readLength;
				while (((readLength = bis.read(buf)) != -1)) {
					servletOS.write(buf, 0, readLength);
				}
				servletOS.flush();
				servletOS.close();
			} catch (Exception e) {
				// ignore for client exception
				logger.error("client hasn't response or client abort connection!",e);
				try {
					servletOS.close();
				} catch (Exception e1) {
				}
			}
			bis.close();
			inputStream.close();
		} catch (Throwable e) {
			logger.error(e.getMessage());
		}

	}
	public static void sendJsonResponse(HttpServletResponse response,JsonVO jsonVO){
		try {		
			JSONArray jsonArray = JSONArray.fromObject( jsonVO.getList() );
			sendStringResponse(response, jsonArray);
		} catch (Throwable e) {
			e.printStackTrace();
		}

	}
	public static void sendStringResponse(HttpServletResponse response,Object obj){
		try {
			System.out.println(obj);
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			String s = (obj!=null)?obj.toString():"error";
			PrintWriter pw = response.getWriter();
			pw.print(s);
			pw.flush();
			pw.close();
//			log.debug("response content: "+(s.length()>100? s.substring(0,100):s));
		} catch (Throwable e) {
			logger.error(e.getMessage());
		}
	}
	public static void main(String[] args){
	}
}
